"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.TranspileAction = void 0;
const chalk_1 = require("chalk");
const inquirer = require("inquirer");
const ui_1 = require("../lib/ui");
const questions_1 = require("../lib/questions/questions");
const abstract_action_1 = require("./abstract.action");
const transpile_1 = require("cpaas-webpack-scripts/scripts/transpile");
const getAllAppPackages_1 = require("cpaas-webpack-scripts/utils/getAllAppPackages");
class TranspileAction extends abstract_action_1.AbstractAction {
    handle(inputs, options) {
        return __awaiter(this, void 0, void 0, function* () {
            const nonInteractive = options.find((option) => option.name === 'nonInteractive').value;
            const isAll = options.find((item) => item.name === 'all').value;
            if (!nonInteractive && !isAll) {
                const paths = require('cpaas-webpack-scripts/config/paths');
                // 如果 cwd 是子模块的目录，就只编译当前模块.
                if (paths.appRootPath === paths.appPath) {
                    yield askForMissingInformation(inputs);
                }
            }
            try {
                let subModules = getSubModules(inputs, options);
                const transpileCommonIfChangeOption = options.find((option) => option.name === 'transpileCommonIfChange');
                if (transpileCommonIfChangeOption &&
                    transpileCommonIfChangeOption.value) {
                    const commonModules = yield transpile_1.transpileCommonIfChange();
                    subModules = subModules.filter((item) => !commonModules.includes(item));
                }
                if (!subModules.length) {
                    if (transpileCommonIfChangeOption &&
                        !transpileCommonIfChangeOption.value) {
                        // 如果没有给子模块，直接编译当前项目
                        yield transpile_1.default();
                    }
                    return;
                }
                // 按照被依赖顺序排序， 一般来说 common 模块要放到前面
                const compareFn = (a, b) => {
                    if (a === 'cpaas-front') {
                        return -10;
                    }
                    if (b === 'cpaas-front') {
                        return 10;
                    }
                    if (a.endsWith('-common') && !b.endsWith('-common')) {
                        return -1;
                    }
                    if (!a.endsWith('-common') && b.endsWith('-common')) {
                        return 1;
                    }
                    return a.localeCompare(b);
                };
                subModules = subModules.sort(compareFn);
                for (const subModuleItem of subModules) {
                    yield transpile_1.default({ subModule: subModuleItem });
                }
            }
            catch (err) {
                if (err instanceof Error) {
                    console.log(`\n${ui_1.ERROR_PREFIX} ${err.message}\n`);
                    console.log(err.stack);
                }
                else {
                    console.error(`\n${chalk_1.default.red(err)}\n`);
                    console.log(err);
                }
                process.exit(1);
            }
        });
    }
}
exports.TranspileAction = TranspileAction;
const getSubModules = (inputs, options) => {
    const subModule = inputs.find((item) => item.name === 'subModule')
        .value;
    let subModules = `${subModule || ''}`
        .trim()
        .split(',')
        .filter((item) => item);
    if (options.find((item) => item.name === 'all').value) {
        const allSubModules = getAllAppPackages_1.getAllAppPackages();
        allSubModules.forEach((item) => {
            if (!subModules.includes(item)) {
                subModules.push(item);
            }
        });
    }
    return subModules;
};
const askForMissingInformation = (inputs) => __awaiter(void 0, void 0, void 0, function* () {
    const nameInput = getSubModuleInput(inputs);
    if (!nameInput.value) {
        const prompt = inquirer.createPromptModule();
        const message = '请选择进行 transpile 的项目?';
        const allSubModules = getAllAppPackages_1.getAllAppPackages();
        if (allSubModules.length === 0) {
            return;
        }
        const questions = [questions_1.generateSelect('subModule')(message)(allSubModules)];
        const answers = yield prompt(questions);
        replaceInputMissingInformation(inputs, answers);
    }
});
const getSubModuleInput = (inputs) => inputs.find((input) => input.name === 'subModule');
const replaceInputMissingInformation = (inputs, answers) => {
    return inputs.map((input) => (input.value =
        input.value !== undefined ? input.value : answers[input.name]));
};
